package com.dlc.yunguang.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.dlc.commonlibrary.ble.UHFR2000Helper;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.dialog.ReadNumsDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.RecyclerViewUtil;
import com.dlc.commonlibrary.utils.ToastUtil;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.yunguang.activitynew.SearchBTActivity;
import com.dlc.yunguang.adapter.QueryRfidAdapter;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.net.bean.RFIDGroupbyGoodsBean;
import com.dlc.yunguang.net.bean.RFIDSpecListBean;
import com.dlc.yunguang.net.bean.StockCheckData;
import com.dlc.yunguang.net.protocol.StockProto;
import com.dlc.yunguang.utils.BluetoothUtil;
import com.dlc.yunguang.R;
import com.seuic.uhf.EPC;

import java.util.ArrayList;
import java.util.List;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018-01-28.
 */

public class QueryRfidActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.item_real_counting_amount)
    CommonItemView itemRealCountingAmount;//扫描到的所有RFID
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.btn_read_rfid)
    Button mBtnReadRfid;

    private DoResultDialog doResultDialog;
    private ReadNumsDialog doReadDialog;

    private ArrayList<String> RfList = new ArrayList<>();//扫描到的所有RFID
    private String startData = "";

    private QueryRfidAdapter mQueryRfidAdapter;

    private int exisNumber = 0;//存在仓库的数据
    private List<StockCheckData> mStockCheckList = new ArrayList<>();
    private boolean isBold, isUnderLine;
    private int record;
    int type;


    private RFIDGroupbyGoodsBean goodsBean;
    private  boolean readState= false;
    @Override
    protected int getLayoutID() {
        return R.layout.activity_query_rfid;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mTitleBar.leftExit(this);
        isBold = false;
        isUnderLine = false;
        doReadRFID();
        doResult();
        InitRecyclerView();
    }

    @OnClick({R.id.btn_read_rfid,R.id.btn_print})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_read_rfid:
                //RfList.add("0002DEF51DBB");
                //RfList.add("0002DEF60035");
                //
                //getDataDetails(RfList);
               getData();
                break;
            case R.id.btn_print:
                print();
                break;
        }
    }
    private void InitRecyclerView(){
        mQueryRfidAdapter = new QueryRfidAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mQueryRfidAdapter.addHeaderView( LayoutInflater.from(QueryRfidActivity.this).inflate(R.layout.item_query_rfid, null, false));
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mRecyclerView, linearLayoutManager);
        mRecyclerView.setAdapter(mQueryRfidAdapter);
    }
    private void doReadRFID() {
        doReadDialog =
                ReadNumsDialog.newDialog(this)
                .setSuccessImage(R.mipmap.ic_success)
                .setSuccessText(getString(R.string.scan_over))
                .setButton("完成扫描", new ReadNumsDialog.OnClickButtonListener() {
                    @Override
                    public void onClickButton(ReadNumsDialog dialog) {
                        readState= false;
                        UHFR2000Helper.getInstance().stopRead();
                    }
                });

        doReadDialog.setCancelable(false);

    }
    private void doResult() {

        doResultDialog = DoResultDialog.newDialog(this)
                .setWorkingText(getString(R.string.commit_counting_result))
                .setSuccessImage(R.mipmap.ic_success)
                .setSuccessText(getString(R.string.commit_counting_result_success));

        doResultDialog.setCancelable(false);


    }

    private void getData(){

        readState= true;
        doReadDialog.showWorking(true);
        UHFR2000Helper.getInstance().readData(new UHFR2000Helper.BleCallBack() {
            @Override
            public void readDatas(List<EPC> data) {
                LogPlus.e("mEPCList="+data.toString());
                RfList.clear();
                if (data.size() > 0){
                    doReadDialog.dismiss();
                    doResultDialog.showResultAndDismiss(true, 1000);

                    String str = "";
                    for (EPC epc : data) {
                        str = epc.getId();
                        if (str.length() > 14) {
                            str = str.substring(str.length() - 12, str.length());
                            RfList.add(str);
                        }
                    }
                    itemRealCountingAmount.setContent(String.valueOf(RfList.size()));
                    getDataDetails(RfList);

                }else {
                    doReadDialog.dismiss();
                    doResultDialog.setFailedText("读取不到RFID");
                    doResultDialog.setFailedImage(R.mipmap.ic_error);
                    doResultDialog.showResultAndDismiss(false, 2000);

                }
            }

            @Override
            public void readNums(final int nums) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (readState){
                            doReadDialog.showWorking(nums);
                        }
                    }
                });

            }
        });
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        }
    };





    private void getDataDetails(final List<String> dflist){
        StringBuilder sb = new StringBuilder();
        for(String rfid : dflist){
            sb.append(rfid+",");
        }
        String data = sb.substring(0,sb.length()-1);
        StockProto.get().rfid_spec_new(data)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<RFIDSpecListBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showOneToast(e.getMessage());
                }

                @Override
                public void onNext(RFIDSpecListBean dataBean) {
                    //mLaundryAdapter.setNewData(dataBean.data);
                    doStockData(dataBean);
                    getrfid_groupby_goods(dflist);
                }
            });
    }
    private void getrfid_groupby_goods(final List<String> dflist){
        goodsBean = null;
        StringBuilder sb = new StringBuilder();
        for(String rfid : dflist){
            sb.append(rfid+",");
        }
        String data = sb.substring(0,sb.length()-1);
        StockProto.get().rfid_groupby_goods(data)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RFIDGroupbyGoodsBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        showOneToast(e.getMessage());
                    }

                    @Override
                    public void onNext(RFIDGroupbyGoodsBean dataBean) {
                        //mLaundryAdapter.setNewData(dataBean.data);
                        goodsBean = dataBean;
                    }
                });
    }

    private void doStockData(RFIDSpecListBean bean){
        mStockCheckList.clear();
        exisNumber = 0;
        if (bean.data!= null&&bean.data.size()>0) {
            for (int i = 0;i < bean.data.size();i++){
                StockCheckData data;
                if (TextUtils.isEmpty(bean.data.get(i).user)) {
                    data  =
                        new StockCheckData(bean.data.get(i).title, bean.data.get(i).count, "0", bean.data.get(i).hotel,
                                getlast(bean.data.get(i).office,bean.data.get(i).lastOffice));
                }else {
                    data  =
                        new StockCheckData(bean.data.get(i).title, bean.data.get(i).count, "0", bean.data.get(i).hotel,
                                getlast(bean.data.get(i).office,bean.data.get(i).lastOffice)+"_"+bean.data.get(i).user);
                }
                exisNumber = exisNumber + Integer.parseInt(bean.data.get(i).count);
                mStockCheckList.add(data);
            }
        }

        //int otherNumber = RfList.size() - exisNumber;
        //if (otherNumber > 0){
        //    StockCheckData data = new StockCheckData("品名为空",String.valueOf(otherNumber),"0");
        //    mStockCheckList.add(data);
        //}
        mQueryRfidAdapter.setNewData(mStockCheckList);
    }

    private void print(){
        List<RFIDGroupbyGoodsBean.DataBean> list = goodsBean.data;
        if (list != null && list.size() > 0) {
            String string = "";

            string = string + "-------------------------";
            string = string + "\r\n" + "实际读取数量："+String.valueOf(RfList.size());
            for (int i = 0; i < list.size(); i++) {
                RFIDGroupbyGoodsBean.DataBean bean = list.get(i);
                string = string + "\r\n" + ("品名：" + bean.goods_name) + ("医院：" + bean.hotel_name);
                string = string + ("科室：" + bean.office_name) + ("数量：" + bean.num);
                string = string + "\r\n";
            }
            string = string + "-------------------------";
            string = string + "\r\n";

            Intent intent = new Intent(getActivity(), SearchBTActivity.class);
            intent.putExtra(SearchBTActivity.key_string, string);
            startActivity(intent);
        }else {
            ToastUtil.show(getActivity(),"数据不能为空");
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothUtil.disconnectBlueTooth(this);
    }


    private String getlast(String office,String lastOffice){
        String aa ;
        if (office.equals("总科")){
            aa =  lastOffice;
        }else {
            aa = office;
        }
        return aa;
    }
}
